#-*- coding:UTF-8-*-

__author__='zhaoxp'

'''
http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/
this shows how to use with
'''

def with_example(filename):
    print('-----how to use with to read file-----')
    print('file is a type of with and you dont have to call f.close() if using with')
    with open(filename) as f:
        print('type fo f is '+str(type(f)))
        for line in f:
            print line.rstrip()
    print('closed file object:')
    print(f)
    print('-----end of with reading file usage-----')

class MyReadFile(object):
    def __init__(self,path):
        print('----- MyReadFile __init__ -----')
        self.f=open(path,'r')
    def __enter__(self):
        print('----- MyReadFile __enter__ -----')
        return self.f
    def __exit__(self,exc_type,exc_value,exc_tb):
        print('----- MyReadFile __exit__ -----')
        if exc_tb is None:
            print('exception is '+str(exc_value))
        else:
            print('normal exit and ready to close file')
        self.f.close()
        print('self.f closing...')
        print(self.f)
        print('===== MyReadFile __exit__ =====')

class DummyResource(object):
    def __init__(self,tag):
        self.tag=tag
        print('Resource [%s]'%tag)
    def __enter__(self):
        print('[Enter %s]: Allocate resource.'%self.tag)
        return self # 可以返回不同的对象
    def __exit__(self,exc_type,exc_value,exc_traceback):
        print('[Exit %s]:Free resrouce.'%self.tag)
        if exc_traceback is None:
            print('[Exit %s]:Exited without exception.'%self.tag)
        else:
            print('[Exit %s]:Exited with exception raised.'%self.tag)
            #print('exception value is ')
            #print(exc_value)
            return False # 可以省略，缺省的None也是被看做是False

if __name__=='__main__':
    with_example(r'with_usage.py')
    print('*'*40)
    with MyReadFile(r'with_usage.py') as f:
        for line in f:
            print line.rstrip()
    print('*'*40)
    with DummyResource('Normal'):
        print('[with-body] Run without exceptions')
    print('*'*40)
    with DummyResource('With-Exception'):
        print('[with-body] Run with exception')
        raise Exception('raised exception')
        print('[with-body] Run with exception. Failed to finish statement-body')
    print('-'*40)

